package com.example.attendancesystem.Handler;



import com.example.attendancesystem.Models.*;
import com.example.attendancesystem.Service.EmpService;
import com.example.attendancesystem.Service.IndexService;
import com.example.attendancesystem.Tools.CheckTimeTools;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/emp")
public class EmpIndexController {

    @Autowired
    private EmpService empService;
    @Autowired
    private IndexService indexService;

    @RequestMapping("/empIndex")
    public String empIndex() {
        return "empIndex";
    }

    /**
     * 获取当前登录的员工session信息
     *
     * @param session session
     * @return Employee对象
     */
    @RequestMapping("/getEmpSession")
    @ResponseBody
    public Employee getEmpSession(HttpSession session) {
        Employee employee;
        employee = (Employee) session.getAttribute("emp");
        return employee;
    }

    /**
     * 湖区当前打卡时间
     *
     * @return CheckTime
     */
    @RequestMapping("/getCheckTime")
    @ResponseBody
    public CheckTime getCheckTime() {
        CheckTime checkTime;
        checkTime = empService.getCheckTime();
        return checkTime;
    }

    /**
     * 查询打卡记录 按日期
     *
     * @param queryDate 查询日期
     * @param session   session
     * @return 数组列表
     */
    @RequestMapping("/getMorClockRow")
    @ResponseBody
    public MorRow getMorClockRow(String queryDate, HttpSession session) {
        Employee employee = (Employee) session.getAttribute("emp");
        //如果传入的日期为空 则查询当天的记录
        if (null == queryDate) {
            SimpleDateFormat date = new SimpleDateFormat("yyyyMMdd");
            queryDate = date.format(new Date());
        }
        //查询返回上午打卡记录
        MorRow morRow;
        morRow = empService.getMorRowByEmpNumberAndDate(employee.getEmpNumber(), queryDate);
        return morRow;
    }

    /**
     * 查询打卡记录 按日期
     *
     * @param queryDate 查询日期
     * @param session   session
     * @return 数组列表
     */
    @RequestMapping("/getAftClockRow")
    @ResponseBody
    public AftRow getAftClockRow(String queryDate, HttpSession session) {
        Employee employee = (Employee) session.getAttribute("emp");
        //如果传入的日期为空 则查询当天的记录
        if (null == queryDate) {
            SimpleDateFormat date = new SimpleDateFormat("yyyyMMdd");
            queryDate = date.format(new Date());
        }
        //查询返回上午打卡记录
        AftRow aftRow;
        aftRow = empService.getAftRowByEmpNumberAndDate(employee.getEmpNumber(), queryDate);
        return aftRow;
    }

    /**
     * 查询是否打卡时间内
     *
     * @return 1001 上午上班 ，1002 上午下班 ，1003 下午上班  ， 1004 下午下班
     */
    @RequestMapping("/getClockBtnState")
    @ResponseBody
    public Integer getClockBtnState() {
        int code = 1005;
        //查询所有打卡时间
        CheckTime checkTime = empService.getCheckTime();
        //将所有的打卡时间与现在的时间作比较 差值的绝对值在30分钟之内 则在打卡时间内
        if (Math.abs(CheckTimeTools.getTimeDifference(checkTime.getMorOnTime())) <= 30) code = 1001;
        if (Math.abs(CheckTimeTools.getTimeDifference(checkTime.getMorOffTime())) <= 30) code = 1002;
        if (Math.abs(CheckTimeTools.getTimeDifference(checkTime.getAftOnTime())) <= 30) code = 1003;
        if (Math.abs(CheckTimeTools.getTimeDifference(checkTime.getAftOffTime())) <= 30) code = 1004;
        return code;
    }

    /**
     * 打卡功能
     *
     * @param session session
     * @return 1001 正常打卡成功， 1002 迟到打卡 ， 1003 早退打卡， 1004 打卡已经打卡了 ，1005 不在打卡时间内 ， 1006 打卡失败
     */
    @RequestMapping("/clickClockBtn")
    @ResponseBody
    public Integer clickClockBtn(HttpSession session) {
        int code = 1006;
        Employee employee = (Employee) session.getAttribute("emp");
        if (null != employee) {
            String empNumber = employee.getEmpNumber();
            String empName = employee.getEmpName();
            code = empService.clickClockBtn(empNumber, empName);
        }
        return code;
    }

    /**
     * 查询新闻前三条
     *
     * @return 返回一个新闻列表
     */
    @RequestMapping("/getNewsLimit")
    @ResponseBody
    public List<News> getNewsLimit() {
        List<News> news;
        news = empService.getNewsLimit();
        return news;
    }

    /**
     * 员工提交一条请假申请
     *
     * @param leaveDate   请假日期
     * @param leaveTime   时间段
     * @param leaveReason 理由
     * @param session     session
     * @return Boolean true成功 false 失败
     */
    @RequestMapping("/addEmpLeaveRequest")
    @ResponseBody
    public Boolean addEmpLeaveRequest(String leaveDate, String leaveTime, String leaveReason, HttpSession session) {
        System.out.println("进来了请假路由");
        Employee employee = (Employee) session.getAttribute("emp");
        LeaveRow leaveRow = new LeaveRow();
        leaveRow.setEmpNumber(employee.getEmpNumber());
        leaveRow.setEmpName(employee.getEmpName());
        leaveRow.setDepartment(employee.getDepartment());
        leaveRow.setEmpPosition(employee.getEmpPosition());
        leaveRow.setLeaveDate(leaveDate);
        leaveRow.setLeaveTime(leaveTime);
        leaveRow.setReason(leaveReason);
        leaveRow.setReadFlag(2);
        leaveRow.setCheckFlag(2);
        leaveRow.setAgreeFlag(2);
        return empService.addEmpLeaveRequest(leaveRow);
    }

    /**
     * 更换头像
     * @param file 文件图片
     * @param session session
     * @return
     */
    @RequestMapping("/updateEmpImg")
    @ResponseBody
    public DataV1 updateEmpImg(MultipartFile file, HttpSession session) {
        //将图片保存到指定的文件加
        //判断图片是否为默认的头像
        //如果是就将上传的图片保存就行
        //如果不是就需要把上一张头像照片删除 然后将新图片保存
        //更新数据库的保存头像的名称
        //替换session信息 因为前端页面 thymeleaf通过Session信息展示的用户头像
        DataV1 dataV1 = new DataV1();
        if (null == file.getOriginalFilename()) {
            dataV1.setCode(0);//上传失败
        } else {
            try {
                Employee employee = (Employee) session.getAttribute("emp");
                String fileName = file.getOriginalFilename();
                String filePath = "F:\\javaproject\\demo5\\src\\main\\resources\\static\\images\\";
                System.out.println(fileName);
                String savaImgName = employee.getEmpNumber() + ".jpg";
                //上传成功 修改 数据库的信息
                if (employee.getImgPath().equals("dafaultEmpImg.jpg")) {

                    /*保存新的图片*/
                    File saveFile = new File(filePath + savaImgName);
                    OutputStream outputStream = new FileOutputStream(saveFile);
                    IOUtils.copy(file.getInputStream(), outputStream);
                    /*更新数据库信息*/
                } else {
                    File oldFile = new File(filePath + employee.getImgPath());
                    oldFile.delete();
                    /*保存新的图片*/
                    File saveFile = new File(filePath + savaImgName);
                    OutputStream outputStream = new FileOutputStream(saveFile);
                    IOUtils.copy(file.getInputStream(), outputStream);
                    /*更新数据库信息*/
                }
                empService.updateEmpImg(employee.getEmpNumber(), savaImgName);
                dataV1.setCode(0);//上传成功 修改 数据库的信息
                Employee newEmployee = indexService.getEmpInfoByNumber(employee.getEmpNumber());
                session.setAttribute("emp", newEmployee);

            } catch (Exception e) {
                e.printStackTrace();
                dataV1.setCode(1);//上传失败
            }
        }
        return dataV1;
    }

    /*主界面查询记录表格*/

    /**
     * 查询员工上午打卡记录
     *
     * @return DataMorRow
     */
    @RequestMapping("/empGetMorRowByDate")
    @ResponseBody
    public DataMorRow getEmpMorRow(HttpSession session, String queryDate) {
        if (null == queryDate) {
            SimpleDateFormat date = new SimpleDateFormat("yyyyMM");
            queryDate = date.format(new Date());
        }
        Employee employee = (Employee) session.getAttribute("emp");
        String empNumber = employee.getEmpNumber();
        DataMorRow dataMorRow;
        dataMorRow = empService.getEmpMorRow(empNumber, queryDate);
        return dataMorRow;

    }

    /**
     * 获取下午打卡记录
     * @param session session
     * @param queryDate 日期
     * @return DataAftRow
     */
    @RequestMapping("/empGetAftRowByDate")
    @ResponseBody
    public DataAftRow getEmpAftRow(HttpSession session, String queryDate) {
        if (null == queryDate) {
            SimpleDateFormat date = new SimpleDateFormat("yyyyMM");
            queryDate = date.format(new Date());
        }
        Employee employee = (Employee) session.getAttribute("emp");
        String empNumber = employee.getEmpNumber();
        DataAftRow dataAftRow;
        dataAftRow = empService.getEmpAftRow(empNumber, queryDate);
        return dataAftRow;
    }


    /**
     * 获取请假信息
     * @param session session
     * @param queryDate 日期
     * @return DataLeaveRow
     */
    @RequestMapping("/empGetLeaveRowByDate")
    @ResponseBody
    public DataLeaveRow getEmpLeaveRow(HttpSession session, String queryDate) {
        if (null == queryDate) {
            SimpleDateFormat date = new SimpleDateFormat("yyyyMM");
            queryDate = date.format(new Date());
        }
        Employee employee = (Employee) session.getAttribute("emp");
        String empNumber = employee.getEmpNumber();
        DataLeaveRow dataLeaveRow;
        dataLeaveRow = empService.getEmpLeaveRow(empNumber, queryDate);
        return dataLeaveRow;
    }


    /**
     * 获取所有新闻
     * @return DataNews
     */
    @RequestMapping("/getAllNews")
    @ResponseBody
    public DataNews getAllNews(String title) {
        if ( null == title){
            title = "%%";
        }else {
            title = "%" + title + "%";
        }
        DataNews dataNews;
        dataNews = empService.getAllNews(title);
        return dataNews;
    }


}
